import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';

import InputWidget from 'widgets/InputWidget.js';
import SelectWidget from 'widgets/SelectWidget.js';
import TextAreaWidget from 'widgets/TextAreaWidget.js';
import TvaProductFormMixin from 'base/views/TvaProductFormMixin.js';

import ModalFormBehavior from 'base/behaviors/ModalFormBehavior.js';
import CatalogComponent from 'common/views/CatalogComponent.js';
import RadioChoiceButtonWidget from 'widgets/RadioChoiceButtonWidget';
import {
    hideRegion,
    showRegion
} from 'backbone-tools';

const template = require('./templates/ProductForm.mustache');

const ProductForm = Mn.View.extend(TvaProductFormMixin).extend({
    partial: false,
    template: template,
    behaviors: [ModalFormBehavior],
    regions: {
        'order': '.field-order',
        'description': '.field-description',
        'mode': '.field-mode',
        'supplier_ht': '.field-supplier_ht',
        'margin_rate': '.field-margin_rate',
        'ht': '.field-ht',
        'quantity': '.field-quantity',
        'unity': '.field-unity',
        'tva_id': '.field-tva_id',
        'product_id': '.field-product_id',
        'catalogContainer': '#catalog-container'
    },
    ui: {
        main_tab: "ul.nav-tabs li:first a",
    },
    // Listen to the current's view events
    events: {},
    // Listen to child view events
    childViewEvents: {
        'catalog:insert': 'onCatalogInsert',
        'mode:change': 'onModeChange',
    },
    // Bubble up child view events
    childViewTriggers: {
        'change': 'data:modified',
        'finish': 'data:modified',
        'cancel:click': 'cancel:click',
    },
    modelEvents: {
        'set:product': 'refreshForm',
        'change:tva_id': 'refreshTvaProductSelect',
    },
    initialize() {
        this.config = Radio.channel('config');
        this.app = Radio.channel('priceStudyApp');
        this.workunit_options = this.config.request(
            'get:options',
            'workunits'
        );
        this.tva_options = this.config.request(
            'get:options',
            'tvas'
        );
        this.product_options = this.config.request(
            'get:options',
            'products',
        );
        this.all_product_options = this.config.request(
            'get:options',
            'products'
        );
    },
    getCommonFieldOptions(attribute, label) {
        let result = {
            field_name: attribute,
            value: this.model.get(attribute),
            label: label,
            editable: true,
        }
        return result;
    },
    refreshForm() {
        this.showOrder();
        this.showDescription();
        this.showModeToggle();
        this.renderModeRelatedFields();
        this.showQuantity();
        this.showUnity();
        this.showTva();
        this.showProduct();
        if (!this.getOption('edit')) {
            this.getUI('main_tab').tab('show');
        }
    },
    renderModeRelatedFields() {
        this.showSupplierHt();
        this.showMarginRate();
        this.showHt();
    },
    showModeToggle() {
        this.showChildView(
            "mode",
            new RadioChoiceButtonWidget({
                field_name: "mode",
                label: "Mode de calcul du prix",
                value: this.model.get('mode'),
                "options": [{
                        'label': 'HT',
                        'value': 'ht'
                    },
                    {
                        'label': "Coût d'achat",
                        'value': 'supplier_ht'
                    },
                ],
                finishEventName: 'mode:change',
            })
        )
    },
    showOrder() {
        this.showChildView(
            'order',
            new InputWidget({
                value: this.model.get('order'),
                field_name: 'order',
                type: 'hidden',
            })
        );
    },
    showDescription() {
        let options = this.getCommonFieldOptions('description', "Description");
        options.description = "Description utilisée dans les devis/factures";
        options.tinymce = true;
        options.required = true;
        options.cid = this.model.cid;
        options.required = true;
        let view = new TextAreaWidget(options);
        this.showChildView('description', view);
    },
    showSupplierHt() {
        const region = this.getRegion('supplier_ht');
        if (this.model.get('mode') == 'supplier_ht') {
            let options = this.getCommonFieldOptions('supplier_ht', "Coût unitaire HT");
            options['required'] = true;
            let view = new InputWidget(options);
            this.showChildView('supplier_ht', view);
            showRegion(region);
        } else {
            hideRegion(region);
        }
    },
    showMarginRate() {
        const region = this.getRegion('margin_rate');
        if (this.model.get('mode') == 'supplier_ht') {
            let options = this.getCommonFieldOptions('margin_rate', 'Coefficient de marge');
            options.description = "Coefficient de marge à appliquer dans les calculs";
            let view = new InputWidget(options);
            this.showChildView('margin_rate', view);
            showRegion(region);
        } else {
            hideRegion(region);
        }
    },
    showHt() {
        const region = this.getRegion('ht');
        if (this.model.get('mode') == 'ht') {
            let options = this.getCommonFieldOptions('ht', 'Montant unitaire HT');
            options['required'] = true;
            let view = new InputWidget(options);
            this.showChildView('ht', view);
            showRegion(region);
        } else {
            hideRegion(region);
        }
    },
    showQuantity() {
        let options = this.getCommonFieldOptions('quantity', "Quantité");
        options.required = true;
        let view = new InputWidget(options);
        this.showChildView('quantity', view);
    },
    showUnity() {
        let options = this.getCommonFieldOptions('unity', "Unité");
        options.options = this.workunit_options;
        options.placeholder = 'Choisir une unité';
        options.id_key = 'value';

        let view = new SelectWidget(options);
        this.showChildView("unity", view);
    },
    showTva() {
        // NB : ici les tva_options sont différentes de celles utilisées dans le reset de la view
        // car elles sont modifiées par le SelectWidget et on perd donc l'info de la
        // tva par défaut
        const tva_options = this.config.request(
            'get:options',
            'tvas'
        );
        let options = this.getCommonFieldOptions('tva_id', 'TVA');
        options.id_key = 'id';
        options.options = tva_options;
        options.required = true;
        options.placeholder = 'Choisir un taux de TVA';
        let view = new SelectWidget(options);
        this.showChildView('tva_id', view);
    },
    showProduct() {
        let options = this.getCommonFieldOptions('product_id', 'Compte produit');
        this.product_options = this.getProductOptions(
            this.tva_options,
            this.all_product_options,
            this.model.get('tva_id'),
        );
        options.required = true;
        options.options = this.product_options;
        options.id_key = 'id';
        options.placeholder = 'Choisir un compte produit';
        let view = new SelectWidget(options);
        this.showChildView('product_id', view);
    },

    templateContext() {
        let title = "Ajouter un produit";
        if (this.getOption('edit')) {
            title = "Modifier un produit";
        }
        return {
            add: !this.getOption('edit'),
            title: title
        };
    },
    onRender() {
        this.refreshForm();
        if (!this.getOption('edit')) {

            this.showChildView(
                'catalogContainer',
                new CatalogComponent({
                    query_params: {
                        type_: 'product'
                    },
                    url: AppOption['catalog_tree_url'],
                    multiple: true
                })
            );
        }
    },
    onCatalogInsert(sale_products) {
        let req = this.app.request('insert:from:catalog', this.getOption("destCollection"), sale_products);
        req.then(() => {
            this.app.trigger('product:changed', this.model);
            this.triggerMethod('modal:close');
        });
    },
    onDestroyModal() {
        this.app.trigger('navigate', 'index');
    },
    onModeChange(key, value) {
        this.model.set(key, value);
        this.renderModeRelatedFields();
    },
    onSuccessSync() {
        this.app.trigger('product:changed', this.model);
    }
});
export default ProductForm
